import os
import random
import tkinter as tk
from tkinter import ttk, scrolledtext, BOTH,Toplevel,PhotoImage,CENTER,Label
import windnd
from PIL import Image
import fitz
from datetime import datetime
from zsm import *

class PDFTool:
    def __init__(self, root):
        self.root = root
        self.root.title("PDF分离/合并工具 By:风二西 2025.02.24")
        self.root.geometry("500x200")

        # 顶部模式选择框架
        mode_frame = ttk.Frame(root)
        mode_frame.pack(pady=1, anchor='w', padx=10)

        # 单选框
        self.mode = tk.StringVar(value="split")
        ttk.Radiobutton(mode_frame, text="PDF分离", variable=self.mode,
                        value="split").pack(side=tk.LEFT)
        ttk.Radiobutton(mode_frame, text="图片合并", variable=self.mode,
                        value="merge").pack(side=tk.LEFT)

        # 消息输出框
        self.msg_text = scrolledtext.ScrolledText(root,height=1,
                                                  wrap=tk.WORD,
                                                  state='disabled',
                                                  bg="Ivory")
        self.msg_text.pack(fill=tk.BOTH, expand=True, padx=10, pady=1)

        # 底部信息栏
        bottom_frame = ttk.Frame(root)
        bottom_frame.pack(side=tk.BOTTOM, fill=tk.X, padx=10, pady=1)
        ttk.Button(bottom_frame, text="赞赏作者",
                   command=self.donate_author).pack(side=tk.LEFT)
        ttk.Label(bottom_frame,
                  text="更多工具、教程，欢迎关注bilibili风二西").pack(side=tk.RIGHT)


        # 绑定拖放事件（关键修复：确保方法已定义）
        windnd.hook_dropfiles(self.root, func=self.handle_drop)

    # 确保以下方法都在类作用域内正确定义（缩进与__init__同级）
    def handle_drop(self, files):  # 修复：正确的类方法定义
        try:
            file_paths = [f.decode('gbk') for f in files]

            if self.mode.get() == "split":
                self.split_pdf(file_paths[0])
            else:
                self.merge_images(file_paths)

        except Exception as e:
            self.show_message(f"错误：{str(e)}", 'error')

    def split_pdf(self, pdf_path):
        try:
            pdf_dir = os.path.dirname(pdf_path)
            base_name = os.path.splitext(os.path.basename(pdf_path))[0]

            while True:
                rand_num = random.randint(1000, 9999)
                output_dir = os.path.join(pdf_dir, f"{base_name}_{rand_num}")
                if not os.path.exists(output_dir):
                    os.makedirs(output_dir)
                    break

            doc = fitz.open(pdf_path)
            total_pages = len(doc)
            for page_num in range(total_pages):
                page = doc.load_page(page_num)
                pix = page.get_pixmap(dpi=150)
                output_path = os.path.join(output_dir, f"page_{page_num + 1:03d}.png")
                pix.save(output_path)
                self.show_message(f"已转换第 {page_num + 1}/{total_pages} 页")

            self.show_message(f"✅ 分离完成！保存到：{output_dir}\n"
                              f"共生成 {total_pages} 个PNG文件", 'success')

        except Exception as e:
            self.show_message(f"❌ 分离失败：{str(e)}", 'error')
        finally:
            if 'doc' in locals():
                doc.close()

    def merge_images(self, image_paths):
        images = []
        try:
            valid_ext = ('.png', '.jpg', '.jpeg')
            for path in image_paths:
                if not path.lower().endswith(valid_ext):
                    raise ValueError("仅支持PNG/JPG格式图片")
                img = Image.open(path)
                if img.mode in ('RGBA', 'LA'):
                    img = img.convert('RGB')
                images.append(img)
                self.show_message(f"已加载：{os.path.basename(path)}")

            first_dir = os.path.dirname(image_paths[0])
            while True:
                rand_num = random.randint(1000, 9999)
                output_path = os.path.join(first_dir, f"pdf_{rand_num}.pdf")
                if not os.path.exists(output_path):
                    break

            images[0].save(output_path, "PDF",
                           resolution=100.0,
                           save_all=True,
                           append_images=images[1:])

            self.show_message(f"✅ 合并完成！保存到：{output_path}\n"
                              f"共合并 {len(images)} 张图片", 'success')

        except Exception as e:
            self.show_message(f"❌ 合并失败：{str(e)}", 'error')
        finally:
            for img in images:
                img.close()

    def show_message(self, message, msg_type='info'):
        timestamp = datetime.now().strftime("%H:%M:%S")
        self.msg_text.configure(state='normal')
        self.msg_text.insert(tk.END, f"[{timestamp}] ", 'timestamp')
        self.msg_text.insert(tk.END, message + '\n', msg_type)
        self.msg_text.see(tk.END)
        self.msg_text.configure(state='disabled')
        self.root.update_idletasks()

    def donate_author(self):
        self.zsm_windows = Toplevel(self.root)
        # 替换窗口浮于上方
        self.zsm_windows.wm_attributes("-topmost", 1)
        self.zsm_windows.title('赞赏作者')
        self.photo1 = PhotoImage(data=zsm123)
        self.zsm1 = Label(self.zsm_windows, image=self.photo1,
                          compound=CENTER)
        self.zsm1.pack(fill=BOTH, expand=True)


if __name__ == "__main__":
    root = tk.Tk()
    style = ttk.Style()
    style.configure('success.TLabel', foreground='green')

    app = PDFTool(root)
    app.msg_text.tag_config('timestamp', foreground='gray')
    app.msg_text.tag_config('success', foreground='darkgreen')
    app.msg_text.tag_config('error', foreground='red')

    root.mainloop()